<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /*
            单词搜索这种典型的岛屿深搜题目,搜索四周
            */
      var exist = function (board, word) {
        let m = board.length
        let n = board[0].length
        function dfs(i, j, index) {
          if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] == 0 || board[i][j] != word[index]) {
            return false
          }
          if (index == word.length - 1) {
            return true
          }
          let temp = board[i][j]
          board[i][j] = 0
          let res =
            dfs(i - 1, j, index + 1) || dfs(i + 1, j, index + 1) || dfs(i, j - 1, index + 1) || dfs(i, j + 1, index + 1)
          //当前搜索点位深度遍历四周
          board[i][j] = temp
          return res
        }
        for (let i = 0; i < board.length; i++) {
          for (let j = 0; j < board[0].length; j++) {
            if (board[i][j] == word[0]) {
              let res = dfs(i, j, 0)
              if (res) return true
            }
          }
        }
        return false
      }
    </script>
  </body>
</html>
